package com.heima.admin.controller.v1;

import com.heima.admin.entity.AdChannel;
import com.heima.admin.service.AdChannelService;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.PUT;
import java.util.List;


@RestController
@RequestMapping("/api/v1/channel")
@Api(tags = "频道管理", description = "频道管理API")
public class AdChannelController {
    @Autowired
    private AdChannelService channelService;

    @ApiOperation(value = "根据名称分页查询频道列表")
    @ApiImplicitParam(name = "dto", value = "频道请求对象", required = true, dataType = "ChannelDto")
    @PostMapping("list")
    public PageResult<ChannelDto> findByPage(@RequestBody ChannelDto dto) {
        return channelService.findByPage(dto);
    }

    /**
     *
     * @param dto
     * @return
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody ChannelDto dto) {
        if (StringUtils.isBlank(dto.getName())) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        AdChannel adChannel = BeanHelper.copyProperties(dto, AdChannel.class);
        channelService.save(adChannel);
        return ResponseResult.ok();
    }


    /**
     * 修改
     * @param dto
     * @return
     */
    @PutMapping("/update")
    public ResponseResult update(@RequestBody ChannelDto dto) {
        AdChannel adChannel = BeanHelper.copyProperties(dto, AdChannel.class);
        channelService.updateById(adChannel);
        return ResponseResult.ok();
    }

    @DeleteMapping("/del/{id}")
    public ResponseResult delete(@PathVariable("id") Integer channelId) {
        AdChannel adChannel = channelService.getById(channelId);
        if (adChannel.getStatus()) {
            throw new LeadException(AppHttpCodeEnum.DATA_CAN_NOT_DEL);
        }
        channelService.removeById(channelId);
        return ResponseResult.ok();
    }


    @GetMapping("/channels")
    public ResponseResult<List<AdChannel>> channels() {
        return ResponseResult.ok(channelService.list());
    }

}
